package com.ttxs.generator.util;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class DirectoryUtils {

    public static void copyDirectory(String sourcePath, String targetPath, String... skipSubTrees) throws IOException {
        Path source = new File(sourcePath).toPath();
        Path target = new File(targetPath).toPath();
        Files.walkFileTree(source, new SimpleFileVisitor<Path>(){
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                for(String subTree: skipSubTrees) {
                    if (dir.endsWith(subTree)) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }
                }
                // 在目标文件夹中创建dir对应的子文件夹
                Path subDir =null;
                if (dir.compareTo(source) == 0) {
                    subDir = target;
                } else {
                    subDir = target.resolve(dir.subpath(source.getNameCount(), dir.getNameCount()));
                }
                Files.createDirectories(subDir);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Path resolve = target.resolve(file.subpath(source.getNameCount(), file.getNameCount()));
                /**
                 * 生成前端静态路由时，仅第一个微服务项目项目需要复制/router/index.js文件
                 */
                if (resolve.getParent().endsWith("router")
                        && resolve.getFileName().endsWith("index.js")
                        && Files.exists(resolve)) {
                    return FileVisitResult.CONTINUE;
                }
                Files.copy(file, resolve, StandardCopyOption.REPLACE_EXISTING);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}
